import { View, StyleSheet, Image, Pressable } from 'react-native'
import { flexCol, compose } from '../../assets/style/common'
import Swiper from 'react-native-swiper'
import { useMemo, Component, ReactNode } from 'react'
export default function CoverSwiperContain(props: { list: any[] }) {
  const staticSwiper = useMemo(() => <CoverSwiper2 list={props.list} />, [])
  return <View style={style.coverSwiperCtn}>{staticSwiper}</View>
}
class CoverSwiper2 extends Component<{ list: any[] }> {
  dots: any[] = []
  list: any = []
  swiperRef: Swiper | null = null

  state = {
    index: 0,
  }
  constructor(prop: { list: any[]; onIndexChanged?: (index: number) => void }) {
    super(prop)
    this.dots = new Array(prop.list.length).fill('')
    this.list = prop.list
    this.setSwiperRef = (ref: Swiper) => (this.swiperRef = ref)
  }
  setSwiperRef: any = ''
  setScroll(i: number) {
    this.swiperRef?.scrollBy(i - this.state.index, true)
  }

  customPagintion(index: number) {
    return (
      <View style={flexCol(style.lineWrap)}>
        {this.dots.map((_, i) => (
          <Pressable
            key={i}
            style={style.line}
            onPress={() => this.setScroll(i)}
          >
            <View
              style={compose(
                style.rect,
                i !== index
                  ? { backgroundColor: '#e1e1e1' }
                  : { backgroundColor: '#ffffff' },
              )}
            />
          </Pressable>
        ))}
      </View>
    )
  }
  onIndexChange(val: number) {
    this.setState({ index: val })
  }
  render(): ReactNode {
    return (
      <Swiper
        ref={this.setSwiperRef}
        style={{ height: '100%' }}
        autoplay={true}
        index={this.state.index}
        autoplayTimeout={5}
        showsButtons={false}
        loop
        renderPagination={index => this.customPagintion(index)}
        showsPagination={true}
        onIndexChanged={index => this.onIndexChange(index)}
      >
        {this.list?.map((item: any) => (
          <Image key={item.id} style={style.bannerImg} source={item.source} />
        ))}
      </Swiper>
    )
  }
}

const style = StyleSheet.create({
  coverSwiperCtn: {
    position: 'relative',
    height: 400,
  },
  bannerImg: {
    height: 400,
    width: '100%',
    resizeMode: 'cover',
  },
  lineWrap: {
    backgroundColor: '#66666622',
    position: 'absolute',
    zIndex: 100,
    bottom: 0,
    paddingHorizontal: 48,
    paddingBottom: 20,
  },
  line: {
    height: 28,
    paddingVertical: 13,
    marginHorizontal: 8,
    flex: 1,
  },
  rect: {
    width: '100%',
    height: '100%',
    borderRadius: 2,
  },
})
